package com.smart.shiro;

import com.smart.pojo.LoginUser;
import com.smart.pojo.Permission;
import com.smart.pojo.User;
import com.smart.req.LoginUserData;
import com.smart.service.IPermissionService;
import com.smart.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    @Autowired
    private IPermissionService permissionService;

    /**
     * 用户授权，查询数据库获取当前登录用户的所有权限数据
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        LoginUser loginUser = (LoginUser) principalCollection.getPrimaryPrincipal();
        System.out.println("检查授权状况的用户：" + loginUser);

        List<Permission> permissionList = permissionService.queryByUserId(loginUser.getId());
        List<String> permsList = permissionList.stream()
                .map(Permission::getPerms)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        System.out.println("查看当前用户的权限:" + permsList);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permsList);

        return info;
    }

    /**
     * 用户登录，查询数据库获取用户登录数据
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userCode = (String) token.getPrincipal();
        System.out.println("登录认证的账号：" + userCode);

        User user = userService.lambdaQuery().eq(User::getUserCode, userCode).one();
        System.out.println("账号详情：" + user);

        if (user == null || user.getStatus() != 0) {
            return null;
        }
        LoginUser loginUser = userService.queryUserInfoById(user.getId());

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                loginUser,
                user.getPassword(),
                ByteSource.Util.bytes(user.getUserCode()),
                "myRealm"
        );

        return info;
    }
}
